#!/bin/bash

# API连接测试脚本

set -e

echo "===== 测试API连接 ====="

# 测试本地API连接
echo "测试本地到 /api/v1/register 的连接..."
curl -v -X OPTIONS http://localhost/api/v1/register 2>&1 | grep -E "(< HTTP|Access-Control)"

echo ""
echo "测试本地API健康端点..."
curl -v http://localhost/health 2>&1 | grep "< HTTP"

# 测试从nginx容器内部到API的连接
echo ""
echo "从nginx容器测试到measurement容器的连接..."
docker compose exec nginx curl -v -s http://measurement:9898/api/v1/register || echo "连接失败"

# 检查后端配置
echo ""
echo "检查后端API路由配置..."
docker compose exec measurement python -c "
import sys
try:
    from app.api import router
    print('路由配置:')
    for route in router.routes:
        print(f'路径: {route.path}, 方法: {route.methods}')
except Exception as e:
    print(f'无法读取路由配置: {e}')
    sys.exit(1)
"

# 检查严格的跨域策略
echo ""
echo "检查API请求头和响应..."
curl -v -X OPTIONS -H "Origin: https://mingyun.online" \
     -H "Access-Control-Request-Method: POST" \
     -H "Access-Control-Request-Headers: Content-Type" \
     https://mingyun.online/api/v1/register 2>&1 | grep -E "(< HTTP|Access-Control)"

echo ""
echo "===== 潜在问题和解决方案 ====="
echo "1. 如果是CORS问题:"
echo "   - 您的Referer Policy 设置为 'strict-origin-when-cross-origin'"
echo "   - 确保前端和后端的域名一致，或正确配置CORS"
echo ""
echo "2. 如果后端路由问题:"
echo "   - 检查API是否正确配置了 /api/v1/register 端点"
echo "   - 确认API路由是否正确映射"
echo ""
echo "3. 如果是请求被重置问题:"
echo "   - 检查后端日志是否有异常"
echo "   - 测试更改请求Content-Type（尝试application/x-www-form-urlencoded或multipart/form-data）"
echo ""
echo "4. 应用修复后重启服务:"
echo "   docker compose restart nginx measurement" 